package com.atguigu.servicebase.handler;

import com.atguigu.commonutils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;


@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody //让后端的数据以json形式返回
public class GlobalExceptionHandler {

	@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
	public Result exceptionHandler(SQLIntegrityConstraintViolationException exception){
		//处理产生的异常
		String message = exception.getMessage();
		String[] s = message.split(" ");
		if(message.contains("Duplicate entry")){
			String msg=s[2]+"已存在";
			return Result.error().message(msg);
		}else {
			return Result.error().message("sql的未知异常");
		}

	}

	/**
	 * 抛出sql除外的异常
	 * @param exception
	 * @return
	 */
	@ExceptionHandler(CustomException.class)
	public Result exceptionHandler(CustomException exception){
		//处理产生的异常->message来源于抛出的异常信息
		String message = exception.getMsg();
		log.error(message);//将错误信息输出到文件中
		return Result.error().code(exception.getCode()).message(message);
	}
}
